package com.cgbl.cg.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.cgbl.cg.BR
import com.cgbl.cg.R
import com.cgbl.cg.adapter.LimitedTimeAdapter
import com.cgbl.cg.databinding.AppFragmentLimitedTimeBinding
import com.cgbl.cg.vm.home.LimitedTimeFraViewModel
import com.robot.base.base.activity.GLBaseFragment
import com.robot.base.model.PreferentPageBean

class LimitedTimeFragment :
    GLBaseFragment<AppFragmentLimitedTimeBinding, LimitedTimeFraViewModel>() {

    private lateinit var moreCourseAdapter: LimitedTimeAdapter
    var typeTab = ""

    companion object {
        fun newInstance(typeTab: String): LimitedTimeFragment {
            val fragment = LimitedTimeFragment()
            val bundle = Bundle()
            bundle.putString("typeTab", typeTab)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int = R.layout.app_fragment_limited_time

    override fun initParam() {
        super.initParam()
        typeTab = arguments?.getString("typeTab") ?: ""

    }

    override fun initVariableId(): Int = BR.viewModel

    override fun initComponents() {
        initAdapter()
    }

    override fun initData() {
        super.initData()
        viewModel.refresh()
    }


    private fun initAdapter() {
        moreCourseAdapter = LimitedTimeAdapter()
        binding.recyclerView.apply {
            adapter = moreCourseAdapter
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        binding.smartRefreshLayout.setOnRefreshListener {
            viewModel.refresh()
        }

        binding.smartRefreshLayout.setOnLoadMoreListener {
            viewModel.load()
        }

        viewModel.uc.refreshEvent.observe(this) {
            binding.smartRefreshLayout.finishRefresh()
            binding.smartRefreshLayout.finishLoadMore()
            binding.smartRefreshLayout.setEnableLoadMore(it != 1)
        }

        viewModel.uc.refreshDataEvent.observe(this) {
            if (viewModel.pageNo == 1) {
                moreCourseAdapter.setNewInstance(it as MutableList<PreferentPageBean>?)
            } else {
                moreCourseAdapter.addData(it)
            }
        }
    }

}